package com.laamella.syntherface.synths.gui;

import javax.swing.AbstractButton;
import javax.swing.BoundedRangeModel;
import javax.swing.ButtonGroup;
import javax.swing.ButtonModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

/**
 * A ButtonGroup that has a BoundedRangeModel that is updated with the index of
 * the selected button.
 */
@SuppressWarnings("serial") public class RotaryButtonGroup extends ButtonGroup {

	private BoundedRangeModel rangeModel;

	public void setModel(BoundedRangeModel model) {
		this.rangeModel = model;
		if (model.getValue() >= buttons.size()) {
			System.out.println("Current value of model is out of range for RotaryButtonGroup.");
		} else {
			setSelected(buttons.get(rangeModel.getValue()).getModel(), true);
		}
		rangeModel.addChangeListener(new ChangeListener() {
			@Override public void stateChanged(ChangeEvent changeevent) {
				setSelected(buttons.get(rangeModel.getValue()).getModel(), true);
			}
		});
	}

	@Override public void setSelected(ButtonModel buttonmodel, boolean flag) {
		super.setSelected(buttonmodel, flag);
		if (rangeModel != null && flag) {
			int index = 0;
			for (AbstractButton button : buttons) {
				if (button.getModel() == buttonmodel) {
					rangeModel.setValue(index);
					return;
				}
				index++;
			}
		}
	}
}
